﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace GlTool.GlHttp
{
    /// <summary>
    /// 请求数据处理
    /// </summary>
    public class GlHttpResponse
    {
        //得到的http请求
        private HttpWebResponse response;

        public HttpWebResponse Response
        {
            get { return response; }
            set { response = value; }
        }

        //获取字符创
        public override String ToString()
        {
            return ToHtml();
        }

        //获取字符创
        public String ToHtml()
        {
            StreamReader reader;
            //GBK编码
            if (response.CharacterSet.ToLower().IndexOf("gb") > -1)
                reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gbk"));
            else
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //UTF-8
            String rs = reader.ReadToEnd();
            reader.Close();
            return rs;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool savaFile(String fileName)
        {
            Stream receiveStream = response.GetResponseStream();

            byte[] buffer = new byte[1024];
            int numBytesToRead = (int)response.ContentLength;
            FileStream fs = new FileStream(fileName, FileMode.Create);
            int len = 0;
            while ((len = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, len);
            }

            fs.Flush();
            fs.Close();
            fs.Dispose();
            receiveStream.Close();
            return true;
        }

        /// <summary>
        /// 关掉请求连接
        /// </summary>
        public void Close()
        {
            response.Close();
        }
    }
}
